package com.example.todoapp.http.controllers;

import com.example.todoapp.data.entities.Tag;
import com.example.todoapp.http.ResponseStruct;
import com.example.todoapp.http.TagCreateRequest;
import com.example.todoapp.http.TagUpdateRequest;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@RestController
public class TagController {

    // 使用静态 List 存储标签数据（内存存储）
    private static final List<Tag> tags = new ArrayList<>();

    // 初始化一些测试数据
    static {
        Tag tag1 = new Tag();
        tag1.setId(1L);
        tag1.setName("test-tag");
        tag1.setDescription("test");
        tag1.setCreatedAt(LocalDateTime.now());
        tag1.setUpdatedAt(LocalDateTime.now());
        tags.add(tag1);

        Tag tag2 = new Tag();
        tag2.setId(2L);
        tag2.setName("test-tag");
        tag2.setDescription("test");
        tag2.setCreatedAt(LocalDateTime.now());
        tag2.setUpdatedAt(LocalDateTime.now());
        tags.add(tag2);
    }

    // 获取所有标签（GET /tags）
    @GetMapping("/tags")
    public ResponseStruct list() {
        return ResponseStruct.wrap(tags);
    }

    // 获取单个标签（GET /tag/{id}）
    @GetMapping("/tag/{id}")
    public ResponseStruct getTagById(@PathVariable Long id) {
        Optional<Tag> foundTag = tags.stream()
                .filter(tag -> tag.getId().equals(id))
                .findFirst();

        return foundTag.map(ResponseStruct::wrap)
                .orElseGet(() -> new ResponseStruct(-1, "Tag not found", null));
    }

    // 新增标签方法
    @PostMapping("/tag")
    public ResponseStruct addTag(@RequestBody TagCreateRequest request) {
        Tag newTag = new Tag();
        newTag.setName(request.getName());
        newTag.setDescription(request.getDescription());
        newTag.setId((long) (tags.size() + 1));
        newTag.setCreatedAt(LocalDateTime.now());
        newTag.setUpdatedAt(LocalDateTime.now());
        tags.add(newTag);
        return ResponseStruct.wrap(newTag);
    }

    // 更新标签（POST /tag/{id}）
    @PostMapping("/tag/{id}")
    public ResponseStruct updateTag(
            @PathVariable Long id,
            @RequestBody TagUpdateRequest request
    ) {
        Optional<Tag> optionalTag = tags.stream()
                .filter(tag -> tag.getId().equals(id))
                .findFirst();

        if (!optionalTag.isPresent()) {
            return new ResponseStruct(-1, "Tag not found", null);
        }

        Tag tag = optionalTag.get();
        if (request.getName() != null) {
            tag.setName(request.getName());
        }
        // 处理拼写不一致问题
        if (request.getDescription() != null) {
            tag.setDescription(request.getDescription());
        } else if (request.getDescriptions() != null) {
            tag.setDescription(request.getDescriptions());
        }
        tag.setUpdatedAt(LocalDateTime.now());

        return ResponseStruct.wrap(tag);
    }
}